package it.okkam.longwell.ui.command;

import it.okkam.webid.model.VerifyWebID;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.apache.velocity.VelocityContext;

import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.tdb.TDBFactory;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.XSD;

import edu.mit.simile.longwell.LongwellServer;
import edu.mit.simile.longwell.login.CheckLogin;
import edu.mit.simile.longwell.login.LoginUtility;
import edu.mit.simile.longwell.ui.FlairMessage;
import edu.mit.simile.longwell.ui.FlairURL;
import edu.mit.simile.longwell.ui.InjectionManager;
import edu.mit.simile.longwell.ui.command.CommandBase;

public class LoginBasicCommand extends CommandBase {
	final static private Logger s_logger = Logger.getLogger(LoginBasicCommand.class);
	CheckLogin check = null;
	final protected String m_template;
	public static boolean userInput = false;
	protected ServletContext context;
	VelocityContext vcContext = null;
	HashMap<String, String> userForSession = new HashMap<String, String>();
	private File fileOutput = new File("/tmp/testLogin.ttl");
	/**
	 * @param injectionManager
	 */
	public LoginBasicCommand(InjectionManager injectionManager, String template) {
		super(injectionManager);
		m_template = template;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * edu.mit.simile.flair.IFlairCommand#execute(edu.mit.simile.flair.FlairMessage
	 * )
	 */
	public void execute(FlairMessage msg) throws ServletException {

		String username = msg.m_request.getParameter("username");
		String password = msg.m_request.getParameter("password");
		// first call for login
		if (!userForSession.containsKey(msg.m_request.getSession().getId())
				&& username == null && password == null) {
			try {
				vcContext = createContext(msg);
				vcContext.put("application", "BCC - Login");
				userForSession.put(msg.m_request.getSession().getId(), "");
				vcContext.put("sessionId", msg.m_request.getSession().getId());
				vcContext.put("hashError", userForSession);
				msg.m_ve.mergeTemplate(m_template, vcContext,
						msg.m_response.getWriter());
				userInput = true;

			} catch (Exception e) {
				s_logger.error(e);
				e.printStackTrace();
			}
		} else if (username == null && password == null) {
			try {
				msg.m_ve.mergeTemplate(m_template, vcContext,
						msg.m_response.getWriter());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// the user has passed username or pwd empty
		else if (username == "" || password == "") {
			s_logger.info("username  or password null");
			try {
				vcContext = createContext(msg);
				vcContext.put("application", "BCC - Login");
				// vcContext.put("error", error);
				userForSession.put(msg.m_request.getSession().getId(),
						"username_null");
				vcContext.put("sessionId", msg.m_request.getSession().getId());
				vcContext.put("hashError", userForSession);
				msg.m_ve.mergeTemplate(m_template, vcContext,
						msg.m_response.getWriter());
				userInput = true;

			} catch (Exception e) {
				s_logger.error(e);
				e.printStackTrace();
			}
		}
		// username and password aren't empty, check login
		else {
			try {
				s_logger.info("try login for user " + username);
				//check = new CheckLogin(msg);
				if (username != null) {
					context = msg.m_servlet.getServletContext();
					String fileName = LongwellServer.getUsersDatasetPath(); 
					boolean isAdmin = VerifyWebID.isAdmin(username, fileName);
					if (CheckLogin.check(username, password, fileName)) {
						msg.getProfile().setUsername(username);
						s_logger.info("********************The user " +username +" has done the basic login************************");
						LoginUtility.saveLogin(username);
						//vcContext = createContext(msg);
						msg.m_response.sendRedirect(new FlairURL(msg)
								.changeCommandQuery("selectDataset", "")
								.toURLString());
					} else {
						s_logger.info("invalid login, redirect on login.vt again");
						vcContext = createContext(msg);
						msg.m_response.sendRedirect(new FlairURL(msg)
								.changeCommandQuery("home", "").toURLString());
						userForSession.put(msg.m_request.getSession().getId(),
								"invalid_login");
						vcContext.put("sessionId", msg.m_request.getSession()
								.getId());
						vcContext.put("hashError", userForSession);
					}
				} else {
					try {
						vcContext = createContext(msg);
						vcContext.put("application", "BCC - Login");
						userForSession.put(msg.m_request.getSession().getId(),
								"invalid_login");
						vcContext.put("sessionId", msg.m_request.getSession()
								.getId());
						vcContext.put("hashError", userForSession);
						// vcContext.put("error", error);
						msg.m_ve.mergeTemplate(m_template, vcContext,
								msg.m_response.getWriter());
						userInput = true;

					} catch (Exception e) {
						s_logger.error(e);
						e.printStackTrace();
					}
				}
			} catch (Exception e) {
				s_logger.error(e);
				e.printStackTrace();
			}
		}
	}
}
